import { Component, OnInit } from '@angular/core';
import { finalize } from 'rxjs/operators';
import { NzMessageService } from 'ng-zorro-antd';

import { PaymentPlugin } from 'src/app/model/payment-plugin';
import { PluginConfig } from 'src/app/model/plugin-config';
import { PluginConfigService } from 'src/app/service/plugin-config.service';


@Component({
  selector: 'app-payment-plugin',
  templateUrl: './payment-plugin.component.html',
  styleUrls: ['./payment-plugin.component.less']
})
export class PaymentPluginComponent implements OnInit {

  // table
  dataList: PaymentPlugin[] = [];
  loading: boolean = true;

  // modal
  isVisible = false;
  isOkLoading = false;

  // form
  selectedPlugin: PaymentPlugin = new PaymentPlugin();
  formData: PluginConfig = new PluginConfig();
  constructor(
    private message: NzMessageService,
    private pluginConfigService: PluginConfigService,
  ) { }

  // table
  loadListData(): void {
    this.loading = true;
    this.pluginConfigService.getPlugins('PaymentPlugin')
      .subscribe((data: PaymentPlugin[]) => {
        this.loading = false;
        this.dataList = data;
      });
  }
  handleInstall(data: PaymentPlugin): void {
    this.pluginConfigService.install(data.id).subscribe(() => {
      this.message.success('操作成功')
      this.loadListData();
    });
  }
  handleUninstall(data: PaymentPlugin): void {
    this.pluginConfigService.uninstall(data.id).subscribe(() => {
      this.message.success('操作成功')
      this.loadListData();
    });
  }
  // modal
  showModal(data: PaymentPlugin): void {
    this.selectedPlugin = data;
    this.loadFormData(data.config);
    this.isVisible = true;
  }

  handleCancel(): void {
    this.isVisible = false;
  }

  handleOk(): void {
    this.isOkLoading = true;
    this.submitForm(this.formData)
      .pipe(finalize(() => this.isOkLoading = false))
      .subscribe(() => {
        this.isVisible = false;
        this.message.success('操作成功')
        this.loadListData();
      });
  }

  // form
  loadFormData(data: PluginConfig): void {
    this.formData = { ...data };
  }

  private submitForm(data: PluginConfig) {
    return this.pluginConfigService.update(data);
  }

  ngOnInit() {
    this.loadListData();
  }

}
